package com.ruoyi.drone.service.impl;

import com.ruoyi.drone.domain.DroneUserProfile;
import com.ruoyi.drone.domain.DroneOrganization;
import com.ruoyi.drone.domain.dto.DroneLoginDTO;
import com.ruoyi.drone.mapper.DroneUserProfileMapper;
import com.ruoyi.drone.mapper.DroneOrganizationMapper;
import com.ruoyi.drone.service.IDroneLoginService;
import com.ruoyi.drone.utils.JwtUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 无人机系统登录服务实现类
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class DroneLoginServiceImpl implements IDroneLoginService {

    @Autowired
    private DroneUserProfileMapper userProfileMapper;

    @Autowired
    private DroneOrganizationMapper organizationMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private JwtUtils jwtUtils;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public String login(DroneLoginDTO loginDTO) {
        // 先查找飞手信息
        DroneUserProfile pilotProfile = userProfileMapper.selectByPhone(loginDTO.getPhone());
        
        Long userId = null;
        String phone = loginDTO.getPhone();
        
        if (pilotProfile != null) {
            // 找到飞手信息
            userId = pilotProfile.getUserId();
            
            // 检查飞手档案状态
            if (!"1".equals(pilotProfile.getStatus())) {
                throw new RuntimeException("飞手档案未通过审核");
            }
        } else {
            // 没找到飞手，再查找组织信息
            DroneOrganization organization = organizationMapper.selectByPhone(loginDTO.getPhone());
            if (organization != null) {
                userId = organization.getUserId();
                
                // 检查组织档案状态
                if (!"1".equals(organization.getStatus())) {
                    throw new RuntimeException("组织档案未通过审核");
                }
            }
        }
        
        if (userId == null) {
            throw new RuntimeException("用户不存在");
        }

        // 根据user_id查询sys_user表获取密码
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser == null) {
            throw new RuntimeException("系统用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), sysUser.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 检查系统用户状态
        if (!"0".equals(sysUser.getDelFlag())) {
            throw new RuntimeException("用户已被删除");
        }

        // 生成JWT token
        return jwtUtils.generateToken(userId, phone);
    }

    @Override
    public boolean validateToken(String token) {
        try {
            return !jwtUtils.isTokenExpired(token);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Long getUserIdFromToken(String token) {
        try {
            return jwtUtils.getUserIdFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String getPhoneFromToken(String token) {
        try {
            return jwtUtils.getPhoneFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }


    @Override
    public String getTokenFromHeader(String authHeader) {
        return jwtUtils.getTokenFromHeader(authHeader);
    }
}
